import React, {useEffect, useState} from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  Image,
  ScrollView,
  TextInput,
} from 'react-native';
import {useNavigation} from '@react-navigation/native';
import AreaView from '../../components/Layout/AreaView';
import {List, DatePicker, Picker, Toast} from '@ant-design/react-native';
import dayjs from 'dayjs';
import {launchImageLibrary} from 'react-native-image-picker';
import {getUserProfile, updateUserProfile} from '../../service/user';
import {upload} from '../../service/common';
import BaseUrl from '../../config/BaseUrl';
import styles from './style';

const Item = List.Item;
const sexData = [
  {label: '男', value: '1'},
  {label: '女', value: '2'},
];
const CustomChildren = (props) => (
  <TouchableOpacity onPress={props.onPress}>
    <View
      style={{
        height: 36,
        paddingLeft: 15,
        flexDirection: 'row',
        alignItems: 'center',
      }}>
      <Text style={{flex: 1}}>{props.children}</Text>
      <Text style={{textAlign: 'right', marginRight: 15}}>
        {props.extra}
      </Text>
    </View>
  </TouchableOpacity>
);
const PersonDetail = () => {
  const navigation = useNavigation();
  const [userProfileData, setUserProfileData] = useState();
  const [isEdit, setIsEdit] = useState(false);
  const [address, setAddress] = useState('');
  const [certNo, setCertNo] = useState('');
  const [custName, setCustName] = useState('');
  const [email, setEmail] = useState('');
  const [nickName, setNickName] = useState('');
  const [phone, setPhone] = useState('');
  const [sex, setSex] = useState();
  const [date, setDate] = useState();
  useEffect(() => {
    _getUserProfile();
  }, []);
  const _getUserProfile = () => {
    getUserProfile().then((res) => {
      console.log(res);
      const profile = res?.data;
      setAddress(profile?.address);
      setCertNo(profile?.certNo);
      setCustName(profile?.custName);
      setEmail(profile?.email);
      setNickName(profile?.nickName);
      setPhone(profile?.phone);
      setSex(profile?.sex);
      setDate(new Date(profile?.birthday));
      setUserProfileData({...profile});
    });
  };
  const submit = () => {
    setIsEdit(true);
    if (!isEdit) {
      return;
    }
    const params = {
      ...userProfileData,
      custId: userProfileData?.custId,
      custName,
      email,
      nickName,
      phone,
      sex: sex && sex[0],
      certNo,
      birthday: dayjs(date).format('YYYY-MM-DD'),
      address,
    };
    console.log(params);
    updateUserProfile(params).then((res) => {
      _getUserProfile();
      setIsEdit(false);
    });
  };
  const photoPress = () => {
    if (!isEdit) {
      return;
    }
    launchImageLibrary(
      {
        mediaType: 'photo',
        includeBase64: false,
      },
      (response) => {
        const file = {
          uri: response.uri,
          name: response.fileName,
          type: 'multipart/form-data',
        };
        let formData = new FormData();
        formData.append('file', file);
        console.log('formdata', JSON.stringify(formData));
        upload(formData).then((res) => {
          console.log(res);
          if (res.code === 200) {
            setUserProfileData({...userProfileData, image: res.imgUrl});
          }
        });
      },
    );
  };
  return (
    <AreaView>
      <ScrollView style={styles.container}>
        <TouchableOpacity
          activeOpacity={1}
          style={styles.avatar}
          onPress={photoPress}>
          <Image
            source={{uri: BaseUrl.imgurl + userProfileData?.image}}
            style={styles.avatar_img}
          />
          {!isEdit && <Text style={styles.avatar_text}>{nickName}</Text>}
        </TouchableOpacity>
        <List>
          {isEdit && (
            <Item
              extra={
                <TextInput
                  value={nickName}
                  placeholder="请输入"
                  style={styles.input}
                  onChangeText={(val) => setNickName(val)}
                />
              }>
              <Text style={styles.list_text}>昵称</Text>
            </Item>
          )}

          <Item
            extra={
              !isEdit ? (
                <Text style={styles.list_text}>{custName || '-'}</Text>
              ) : (
                <TextInput
                  value={custName}
                  placeholder="请输入"
                  style={styles.input}
                  onChangeText={(val) => {
                    setCustName(val);
                  }}
                />
              )
            }>
            <Text style={styles.list_text}>姓名</Text>
          </Item>
        </List>
        <List>
          {isEdit ? (
            <Picker
              data={sexData}
              cols={1}
              value={sex}
              onChange={(val) => setSex(val)}>
              {/* <List.Item
                extra={
                  <Text style={styles.list_text}>
                    {sex === '0' ? '男' : '女'}
                  </Text>
                }>
                <Text style={styles.list_text}>性别</Text>
              </List.Item> */}
              <CustomChildren>性别</CustomChildren>
            </Picker>
          ) : (
            <Item
              extra={
                <Text style={styles.list_text}>
                  {sex === '1' ? '男' : '女'}
                </Text>
              }>
              <Text style={styles.list_text}>性别</Text>
            </Item>
          )}
        </List>
        <List>
          {isEdit ? (
            <DatePicker
              mode="date"
              value={date}
              minDate={new Date(1900, 7, 6)}
              maxDate={new Date()}
              onChange={(val) => {
                console.log(val);
                setDate(val);
              }}
              format="YYYY-MM-DD">
              <CustomChildren>生日</CustomChildren>
            </DatePicker>
          ) : (
            <Item
              extra={
                <Text style={styles.list_text}>
                  {dayjs(date).format('YYYY-MM-DD')}
                </Text>
              }>
              <Text style={styles.list_text}>生日</Text>
            </Item>
          )}
        </List>
        <List>
          <Item
            extra={
              !isEdit ? (
                <Text style={styles.list_text}>{phone || '-'}</Text>
              ) : (
                <TextInput
                  keyboardType="numeric"
                  disabled={!isEdit}
                  placeholder="请输入"
                  value={phone}
                  style={styles.input}
                  onChangeText={(val) => {
                    setPhone(val);
                  }}
                />
              )
            }>
            <Text style={styles.list_text}>手机号</Text>
          </Item>
          <Item
            extra={
              !isEdit ? (
                <Text style={styles.list_text}>{certNo || '-'}</Text>
              ) : (
                <TextInput
                  disabled={!isEdit}
                  placeholder="请输入"
                  value={certNo}
                  style={styles.input}
                  onChangeText = {(val) => {
                    setCertNo(val)}
                  }
                  onBlur = { () => {
                      if (!(/(^\d{15}$)|(^\d{17}([0-9]|X|x)$)/.test(certNo))) {
                        Toast.info('请输入合法身份证号');
                        setCertNo('');
                      }
                    }
                  }
                />
              )
            }>
            <Text style={styles.list_text}>身份证号</Text>
          </Item>
          <Item
            extra={
              !isEdit ? (
                <Text style={styles.list_text}>{email || '-'}</Text>
              ) : (
                <TextInput
                  disabled={!isEdit}
                  placeholder="请输入"
                  value={email}
                  style={styles.input}
                  onChangeText={(val) => {
                    setEmail(val)
                  }}
                />
              )
            }>
            <Text style={styles.list_text}>邮件地址</Text>
          </Item>
          <Item
            extra={
              !isEdit ? (
                <Text style={styles.list_text}>{address || '-'}</Text>
              ) : (
                <TextInput
                  disabled={!isEdit}
                  placeholder="请输入"
                  value={address}
                  style={styles.input}
                  onChangeText={(val) => setAddress(val)}
                />
              )
            }>
            <Text style={styles.list_text}>联系地址</Text>
          </Item>
        </List>
        <View style={styles.edit_container}>
          <TouchableOpacity
            activeOpacity={1}
            style={styles.edit_btn}
            onPress={submit}>
            <Text style={styles.btn_text}>{isEdit ? '保存' : '编辑'}</Text>
          </TouchableOpacity>
        </View>
      </ScrollView>
    </AreaView>
  );
};

export default PersonDetail;
